package com.acane.instagram.feature.post

import android.content.Context
import android.net.Uri
import android.util.Log
import android.webkit.MimeTypeMap
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import coil.compose.rememberImagePainter
import com.acane.instagram.R
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.feature.me.MeViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

// 主界面
@Composable
fun PostFlowScreen(
    viewModel: PostViewModel = viewModel(),
    meViewModel: MeViewModel = viewModel(),
    toMain: () -> Unit,
    ) {
    val context = LocalContext.current
    val navController = rememberNavController()

    NavHost(navController, startDestination = "gallery") {
        composable("gallery") {
            GalleryScreen(onPhotosSelected = { uris ->
                viewModel.setSelectedImages(uris)
                navController.navigate("uploadPreview")
            })
        }
        composable("edit") {
            EditScreen(viewModel = viewModel,
                meViewModel = meViewModel,
                onBack = { navController.popBackStack() },
                onPost = {
                    viewModel.postContent(context, meViewModel)
                    navController.navigate("publishing")
                    toMain()
                }
            )
        }
        composable("publishing") {
            PublishingScreen(onComplete = {
                navController.popBackStack(
                    "gallery",
                    inclusive = false
                )
            })
        }
        composable("uploadPreview") {
            UploadMediaScreen(
                viewModel = viewModel, navController = navController
            )
        }
    }
}


@Composable
fun GalleryScreen(onPhotosSelected: (List<Uri>) -> Unit) {
    val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.OpenMultipleDocuments()
    ) { uris ->
        if (uris.isNotEmpty()) {
            onPhotosSelected(uris.toList())
        }
    }
    Button(onClick = {
        launcher.launch(arrayOf("image/*", "video/*"))
    }) {
        Text("选择图片或视频")
    }

}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UploadMediaScreen(
    viewModel: PostViewModel,
    navController: NavHostController,
) {
    val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.OpenMultipleDocuments()
    ) { uris ->
        if (uris.isNotEmpty()) {
            viewModel.selectedImageUris += uris.toList()
        }
    }
    Scaffold(topBar = {
        TopAppBar(navigationIcon = {
            IconButton(onClick = {
                navController.popBackStack()
            }) {
                Icon(Icons.Default.ArrowBack, null)
            }
        }, title = { }, actions = {

        })
    }) { padding ->

        Column(
            modifier = Modifier.padding(padding)
        ) {
            LazyRow(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,

                ) {
                items(viewModel.selectedImageUris) { uri ->
                    val context = LocalContext.current
                    val isVideo = remember(uri) {
                        val fileExtension = getExtensionFromUri(context, uri)
                        Log.d("EditScreen", "File Extension: $fileExtension") // 添加日志
                        listOf("mp4", "avi", "mkv", "mov", "webm", "flv", "wmv").contains(
                            fileExtension
                        )
                    }
                    if (isVideo) {
                        println("Video URI: $uri")
                        UploadVideoPlayerWithThumbnail(uri.toString(),  viewModel)
                    } else {
                        Box(
                            modifier = Modifier.padding(5.dp)
                        ) {
                            Image(
                                painter = rememberImagePainter(uri),
                                contentDescription = null,
                                modifier = Modifier
                                    .size(350.dp)
                                    .clip(RoundedCornerShape(8.dp))
                                    .clickable { /* 处理点击事件 */ },
                                //    .padding(5.dp),
                                contentScale = ContentScale.Crop
                            )
                        }

                    }
                }
                item {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Center,
                    ) {
                        Image(painter = painterResource(id = R.drawable.more_media),
                            contentDescription = null,
                            modifier = Modifier
                                .size(100.dp)
                                .aspectRatio(1f)
                                .clickable {
                                    launcher.launch(arrayOf("image/*", "video/*"))
                                })
                    }

                }
            }
            Spacer(modifier = Modifier.weight(1f))
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.End,
                modifier = Modifier.padding(end = 16.dp, bottom = 16.dp)
            ) {
                Spacer(modifier = Modifier.weight(1f))
                // 继续按钮
                Box(
                    modifier = Modifier
                        .width(80.dp)
                        .height(40.dp)
                        .padding(start = 10.dp),
                ) {
                    androidx.compose.material3.Button(
                        colors = ButtonDefaults.buttonColors(
                            containerColor = InstagramBlue, contentColor = Color.White
                        ),
                        modifier = Modifier.fillMaxSize(),
                        onClick = {
                            navController.navigate("edit")
                        },
                        shape = RoundedCornerShape(15.dp),
                        elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                        contentPadding = PaddingValues(0.dp) // 设置内容内边距
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.Center,
                            modifier = Modifier.padding(horizontal = 5.dp)
                        ) {
                            Text(
                                text = "继续",
                                fontSize = 12.sp,
                            )
                            Image(
                                painter = painterResource(id = R.drawable.arrow_right_white),
                                contentDescription = null,
                                modifier = Modifier.size(16.dp)
                            )

                        }

                    }
                }
            }
        }

    }
}

// 编辑界面
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun EditScreen(
    viewModel: PostViewModel,
    onBack: () -> Unit,
    onPost: () -> Unit,
    meViewModel: MeViewModel,
) {
    val tags = viewModel.tags.collectAsState()
    val context = LocalContext.current

    val recommendTags = viewModel.recommendedTags.collectAsState()

    // 获取模拟数据
    LaunchedEffect(Unit) {
        viewModel.getTagTestData()
    }

    var shareOption: String by remember { mutableStateOf("所有人") }
    var showOption: String by remember { mutableStateOf("主网格和Reels网格") }

    val showRange = viewModel.showRange.collectAsState()
    val shareRange = viewModel.shareRange.collectAsState()

    val scope = rememberCoroutineScope() // 创建协程作用域
    val shareBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val homePageInfoBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val tagBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        ModalBottomSheetLayout(
            sheetState = homePageInfoBottomSheetState,
            sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
            sheetContent = {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
                ) {
                    // 添加 Bar
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                    }
                    // 主要内容区域
                    item {
                        Column(

                        ) {
                            //Spacer(modifier = Modifier.height(20.dp))
                            Text(
                                text = "主页信息显示",
                                fontSize = 18.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                            Spacer(modifier = Modifier.height(10.dp))
                            Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
                            Spacer(modifier = Modifier.height(10.dp))
                            Text(
                                text = "这条Reels可在你主页的哪些位置显示?",
                                fontSize = 15.sp,
                            )
                            Spacer(modifier = Modifier.height(15.dp))
                            Row(verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickableNoRipple {
                                        showOption = "主网格和Reels网格"
                                        viewModel.updateShowRange("grid_and_reels")
                                    }) {
                                Image(painter = painterResource(id = R.drawable.grid),
                                    contentDescription = null,
                                    modifier = Modifier
                                        .size(30.dp)
                                        .clickable {
                                            scope.launch {
                                                homePageInfoBottomSheetState.show()
                                            }
                                        })
                                Spacer(modifier = Modifier.width(10.dp))
                                Text(
                                    text = "主网格和Reels网格",
                                    fontSize = 15.sp,
                                )
                                Spacer(modifier = Modifier.weight(1f))
                                Image(
                                    painter = painterResource(id = if (showOption == "主网格和Reels网格") R.drawable.circle_selected else R.drawable.circle_unselected),
                                    contentDescription = null,
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                            Spacer(modifier = Modifier.height(20.dp))
                            Row(verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickableNoRipple {
                                        showOption = "仅限Reels网格"
                                        viewModel.updateShowRange("reels")
                                    }) {
                                Image(painter = painterResource(id = R.drawable.video),
                                    contentDescription = null,
                                    modifier = Modifier
                                        .size(30.dp)
                                        .clickable {
                                            scope.launch {
                                                shareBottomSheetState.show()
                                            }
                                        })
                                Spacer(modifier = Modifier.width(10.dp))
                                Text(
                                    text = "仅限Reels网格",
                                    fontSize = 15.sp,
                                )
                                Spacer(modifier = Modifier.weight(1f))
                                Image(
                                    painter = painterResource(id = if (showOption == "仅限Reels网格") R.drawable.circle_selected else R.drawable.circle_unselected),
                                    contentDescription = null,
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                            Row(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                androidx.compose.material3.Button(
                                    onClick = {
                                        scope.launch {
                                            homePageInfoBottomSheetState.hide()
                                        }
                                    },
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = InstagramBlue, contentColor = Color.White
                                    ),
                                    shape = RoundedCornerShape(10.dp),
                                    modifier = Modifier
                                        .padding(top = 25.dp)
                                        .width(400.dp)
                                ) {
                                    Text(text = "完成")
                                }
                            }
                        }
                    }
                }
            }) {
            Scaffold(
                topBar = {
                    TopAppBar(navigationIcon = {
                        IconButton(onClick = onBack) {
                            Icon(Icons.Default.ArrowBack, null)
                        }
                    }, title = {
                        Text(
                            text = "新帖子", fontWeight = FontWeight.Bold, fontSize = 18.sp
                        )
                    }, actions = {
                        TextButton(onClick = { onPost() }) {
                            Text(
                                text = "分享", color = InstagramBlue, fontSize = 18.sp
                            )
                        }
                    })
                },
                contentColor = Color.White,
            ) { padding ->

                Column(
                    modifier = Modifier.padding(padding)
                ) {
                    LazyRow(
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically,

                        ) {
                        items(viewModel.selectedImageUris) { uri ->
                            val isVideo = remember(uri) {
                                val fileExtension = getExtensionFromUri(context, uri)
                                Log.d("EditScreen", "File Extension: $fileExtension") // 添加日志
                                listOf("mp4", "avi", "mkv", "mov", "webm", "flv", "wmv").contains(
                                    fileExtension
                                )
                            }
                            if (isVideo) {
                                println("Video URI: $uri")
                                UploadVideoPlayerWithThumbnail(uri.toString(), viewModel)
                            } else {
                                Box(
                                    modifier = Modifier.padding(5.dp)
                                ) {
                                    Image(
                                        painter = rememberImagePainter(uri),
                                        contentDescription = null,
                                        modifier = Modifier
                                            .size(350.dp)
                                            .clip(RoundedCornerShape(8.dp))
                                            .clickable { /* 处理点击事件 */ },
                                        //    .padding(5.dp),
                                        contentScale = ContentScale.Crop
                                    )
                                }

                            }
                        }
                    }
                    TextField(value = viewModel.caption,
                        onValueChange = { viewModel.caption = it },
                        placeholder = { Text("添加说明...", color = Color.Gray) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp),
                        colors = TextFieldDefaults.textFieldColors(
                            backgroundColor = Color.Transparent, // 设置背景颜色为透明
                            focusedIndicatorColor = Color.Transparent, // 设置聚焦时的指示线颜色为透明
                            unfocusedIndicatorColor = Color.Transparent, // 设置未聚焦时的指示线颜色为透明
                        ),
                        textStyle = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.onSurface) // 设置文本颜色
                    )
                    Spacer(Modifier.height(16.dp))
                    Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
                    LazyColumn(

                    ) {
                        item {
                            Spacer(Modifier.height(16.dp))
                            Row(verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        scope.launch {
                                            shareBottomSheetState.show()
                                        }
                                    }) {
                                Spacer(Modifier.width(10.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.eye_share),
                                    contentDescription = null,
                                    modifier = Modifier.size(30.dp)
                                )
                                Spacer(Modifier.width(10.dp))
                                Text(
                                    text = "分享对象", fontSize = 15.sp, color = Color.Black
                                )
                                Spacer(Modifier.weight(1.0f))
                                Text(
                                    text = shareOption, fontSize = 12.sp, color = InstagramDarkGray
                                )
                                Spacer(Modifier.width(10.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.arrow_forward),
                                    contentDescription = null,
                                    modifier = Modifier.size(15.dp)
                                )
                            }
                        }

                        item {
                            Spacer(Modifier.height(16.dp))
                            Row(verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        scope.launch {
                                            homePageInfoBottomSheetState.show()
                                        }
                                    }) {
                                Spacer(Modifier.width(10.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.grid),
                                    contentDescription = null,
                                    modifier = Modifier.size(30.dp)
                                )
                                Spacer(Modifier.width(10.dp))
                                Text(
                                    text = "主页信息显示", fontSize = 15.sp, color = Color.Black
                                )
                                Spacer(Modifier.weight(1.0f))
                                Text(
                                    text = showOption, fontSize = 12.sp, color = InstagramDarkGray
                                )
                                Spacer(Modifier.width(10.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.arrow_forward),
                                    contentDescription = null,
                                    modifier = Modifier.size(15.dp)
                                )
                            }
                        }

                        item {
                            Spacer(Modifier.height(16.dp))
                            Row(verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        scope.launch {
                                            tagBottomSheetState.show()
                                        }
                                    }) {
                                Spacer(Modifier.width(10.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.pound),
                                    contentDescription = null,
                                    modifier = Modifier.size(30.dp)
                                )
                                Spacer(Modifier.weight(1.0f))
                                Text(
                                    text = "添加主题", fontSize = 12.sp, color = InstagramDarkGray
                                )
                                Spacer(Modifier.width(10.dp))
                                Image(
                                    painter = painterResource(id = R.drawable.arrow_forward),
                                    contentDescription = null,
                                    modifier = Modifier.size(15.dp)
                                )
                            }
                        }
                    }
                }

            }
            ModalBottomSheetLayout(
                sheetState = shareBottomSheetState,
                sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
                sheetContent = {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
                    ) {
                        // 添加 Bar
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .wrapContentSize(align = Alignment.Center)
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.bar_horizontal),
                                    contentDescription = "bar",
                                )
                            }
                        }
                        // 主要内容区域
                        item {
                            Column(

                            ) {
                                // Spacer(modifier = Modifier.height(20.dp))
                                Text(
                                    text = "主页信息显示",
                                    fontSize = 18.sp,
                                    modifier = Modifier.align(Alignment.CenterHorizontally)
                                )
                                Spacer(modifier = Modifier.height(10.dp))
                                Divider(
                                    modifier = Modifier.fillMaxWidth(), color = InstagramLightGray
                                )
                                Spacer(modifier = Modifier.height(10.dp))
                                Text(
                                    text = "这条Reels可在你主页的哪些位置显示?",
                                    fontSize = 15.sp,
                                )
                                Spacer(modifier = Modifier.height(20.dp))
                                Row(verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickableNoRipple {
                                            shareOption = "所有人"
                                            viewModel.updateShareRange("public")
                                        }) {
                                    Image(painter = painterResource(id = R.drawable.charm_people),
                                        contentDescription = null,
                                        modifier = Modifier
                                            .size(30.dp)
                                            .clickable {})
                                    Spacer(modifier = Modifier.width(10.dp))
                                    Text(
                                        text = "所有人",
                                        fontSize = 15.sp,
                                    )
                                    Spacer(modifier = Modifier.weight(1f))
                                    Image(
                                        painter = painterResource(id = if (shareOption == "所有人") R.drawable.circle_selected else R.drawable.circle_unselected),
                                        contentDescription = null,
                                        modifier = Modifier.size(20.dp)
                                    )
                                }
                                Spacer(modifier = Modifier.height(15.dp))
                                Row(verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickableNoRipple {
                                            shareOption = "私人"
                                            viewModel.updateShareRange("private")
                                        }) {
                                    Image(painter = painterResource(id = R.drawable.lock),
                                        contentDescription = null,
                                        modifier = Modifier
                                            .size(30.dp)
                                            .clickable {})
                                    Spacer(modifier = Modifier.width(10.dp))
                                    Text(
                                        text = "私人",
                                        fontSize = 15.sp,
                                    )
                                    Spacer(modifier = Modifier.weight(1f))
                                    Image(
                                        painter = painterResource(id = if (shareOption == "私人") R.drawable.circle_selected else R.drawable.circle_unselected),
                                        contentDescription = null,
                                        modifier = Modifier.size(20.dp)
                                    )
                                }
                                Row(
                                    modifier = Modifier.fillMaxWidth()
                                ) {
                                    androidx.compose.material3.Button(
                                        onClick = {
                                            scope.launch {
                                                shareBottomSheetState.hide()
                                            }
                                        },
                                        colors = ButtonDefaults.buttonColors(
                                            containerColor = InstagramBlue,
                                            contentColor = Color.White
                                        ),
                                        shape = RoundedCornerShape(10.dp),
                                        modifier = Modifier
                                            .padding(top = 25.dp)
                                            .width(400.dp)
                                    ) {
                                        Text(text = "完成")
                                    }
                                }
                            }

                        }
                    }
                }) {}
            ModalBottomSheetLayout(
                sheetState = tagBottomSheetState,
                sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
                sheetContent = {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
                    ) {
                        // 添加 Bar
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .wrapContentSize(align = Alignment.Center)
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.bar_horizontal),
                                    contentDescription = "bar",
                                )
                            }
                        }
                        // 主要内容区域
                        item {
                            Column(

                            ) {
                                // Spacer(modifier = Modifier.height(20.dp))
                                Text(
                                    text = "添加主题",
                                    fontSize = 18.sp,
                                    modifier = Modifier.align(Alignment.CenterHorizontally)
                                )
                                Spacer(modifier = Modifier.height(10.dp))
                                Divider(
                                    modifier = Modifier.fillMaxWidth(), color = InstagramLightGray
                                )
                                Spacer(modifier = Modifier.height(10.dp))
                                Text(
                                    text = "使用现有主题或者自定义主题",
                                    fontSize = 15.sp,
                                )
                                Spacer(modifier = Modifier.height(20.dp))
                                // 显示还能添加多少数量的主题（最多添加三个主题）
                                Row(verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickableNoRipple {

                                        }
                                )
                                {
                                    Text(
                                        text = "还可以添加 ${3 - viewModel.tags.value.size} 个主题",
                                        fontSize = 12.sp,
                                        color = InstagramDarkGray
                                    )
                                }
                                Spacer(modifier = Modifier.height(15.dp))
                                // 已经选择的主题列表
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickableNoRipple {

                                        }
                                )
                                {
                                    tags.value.forEach {
                                        Box(
                                            modifier = Modifier
                                                .padding(10.dp)
                                                .width(50.dp)
                                                .height(30.dp)
                                                .align(Alignment.CenterVertically)
                                                .background(
                                                    color = InstagramBlue,
                                                    shape = RoundedCornerShape(8.dp)
                                                )
                                                .clickableNoRipple {
                                                    // 点击从tags中删除
                                                    viewModel.removeTag(it)
                                                }
                                        ) {
                                            Text(
                                                text = "#${it.name}",
                                                fontSize = 12.sp,
                                                color = Color.White,
                                                modifier = Modifier.padding(end = 10.dp)
                                            )
                                        }

                                    }
                                }
                                Spacer(modifier = Modifier.height(15.dp))
                                // 显示推荐主题和待选择的主题
                                LazyRow(
                                    modifier = Modifier.fillMaxWidth(),
                                ) {
                                    item {
                                        recommendTags.value.forEach {
                                            Box(
                                                modifier = Modifier
                                                    .padding(10.dp)
                                                    .width(50.dp)
                                                    .height(30.dp)
                                                    .background(
                                                        color = InstagramDarkGray,
                                                        shape = RoundedCornerShape(8.dp)
                                                    )
                                                    .align(Alignment.CenterHorizontally)
                                                    .clickableNoRipple {
                                                        if (viewModel.tags.value.size < 3) {
                                                            // 点击添加到tags中
                                                            viewModel.addTag(it)
                                                        } else {
                                                            // 显示提示信息
                                                            Toast.makeText(
                                                                context,
                                                                "最多只能添加三个主题",
                                                                Toast.LENGTH_SHORT
                                                            ).show()
                                                        }

                                                    }
                                            ) {
                                                Text(
                                                    text = "#${it.name}",
                                                    fontSize = 12.sp,
                                                    color = Color.White,
                                                    modifier = Modifier
                                                )
                                            }
                                        }
                                    }

                                }
                            }

                        }
                        // 继续按钮
                        item {
                            Row(
                                horizontalArrangement = Arrangement.End
                            ) {
                                Spacer(modifier = Modifier.weight(1.0f))
                                Box(
                                    modifier = Modifier
                                        .width(80.dp)
                                        .height(40.dp)
                                        .padding(start = 10.dp),
                                ) {
                                    androidx.compose.material3.Button(
                                        colors = ButtonDefaults.buttonColors(
                                            containerColor = InstagramBlue,
                                            contentColor = Color.White
                                        ),
                                        modifier = Modifier.fillMaxSize(),
                                        onClick = {
                                            scope.launch {
                                                // 关闭抽屉
                                                tagBottomSheetState.hide()
                                            }
                                        },
                                        shape = RoundedCornerShape(15.dp),
                                        elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                        contentPadding = PaddingValues(0.dp) // 设置内容内边距
                                    ) {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.Center,
                                            modifier = Modifier.padding(horizontal = 5.dp)
                                        ) {
                                            Text(
                                                text = "继续",
                                                fontSize = 12.sp,
                                            )
                                            Image(
                                                painter = painterResource(id = R.drawable.arrow_right_white),
                                                contentDescription = null,
                                                modifier = Modifier.size(16.dp)
                                            )

                                        }

                                    }
                                }
                            }
                        }
                    }
                }) {}
        }
    }
}


// 修改后的 getExtensionFromUri 函数，移除 LocalContext.current 并通过参数传递 Context
fun getExtensionFromUri(context: Context, uri: Uri): String? {
    val contentResolver = context.contentResolver
    val mimeType = contentResolver.getType(uri)
    return if (mimeType != null) {
        MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)?.lowercase()
    } else {
        uri.lastPathSegment?.substringAfterLast(".")?.lowercase()
    }
}


// 发布状态界面
@Composable
fun PublishingScreen(onComplete: () -> Unit) {
    LaunchedEffect(Unit) {
        delay(2000) // 模拟上传时间
        onComplete()
    }

    Box(
        modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            CircularProgressIndicator()
            Spacer(Modifier.height(16.dp))
            Text("Sharing...")
        }
    }
}

// 辅助组件 - 位置选择行
@Composable
private fun LocationRow(viewModel: PostViewModel) {
    Row(modifier = Modifier
        .fillMaxWidth()
        .clickable { /* 打开位置选择 */ }
        .padding(16.dp),
        verticalAlignment = Alignment.CenterVertically) {
        Icon(Icons.Default.LocationOn, null)
        Spacer(Modifier.width(16.dp))
        Text(
            text = viewModel.location.ifEmpty { "Add Location" },
            color = if (viewModel.location.isEmpty()) MaterialTheme.colors.onSurface.copy(alpha = 0.5f)
            else MaterialTheme.colors.onSurface
        )
    }
}